package cn.enjoy.tool.juc;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author K
 * @date 2021/8/2 下午2:14
 */
public class ReadWriteLockTest {
    static Map<String, Object> map = new HashMap<>();
    static ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    static Lock r = rwl.readLock();
    static Lock w = rwl.writeLock();

    /**
     * 读（都是读取操作不会被阻塞，如果前面有写操作，会被阻塞）
     */
    public static final Object get(String key) {
        r.lock();
        try {
            return map.get(key);
        } finally {
            r.unlock();
        }
    }

    /**
     * 写（阻塞）
     */
    public static final Object put(String key, Object value) {
        w.lock();
        try {
            return map.put(key, value);
        } finally {
            w.unlock();
        }
    }

    /**
     * 清除（阻塞）
     */
    public static final void clear() {
        r.lock();
        try {
            map.clear();
        } finally {
            r.unlock();
        }
    }

}
